package evan.curtis.beersnob;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import evan.curtis.beersnob.util.Constants;
import evan.curtis.beersnob.util.DatabaseFunctions;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity {

	private EditText usernameField;
	private EditText passwordField;
	private Button loginButton;
	private String username;
	private String password;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.login);

		usernameField = (EditText) findViewById(R.id.userName);
		passwordField = (EditText) findViewById(R.id.userPassword);
		loginButton = (Button) findViewById(R.id.loginButton);

	}

	public void onClick(View v) {
		username = usernameField.getText().toString();
		password = passwordField.getText().toString();
		new LoginOperation().execute(username, password);
	}

	private void checkUserNameAndPassword(JSONArray databaseValues) throws JSONException {
		
		//if JSONArray is empty, then there is no user in the database
		if (databaseValues.length() == 0) {
			Toast.makeText(this, "User does not exist", Toast.LENGTH_LONG).show();
			
		}

		for (int i = 0; i < databaseValues.length(); i++) {
			JSONObject json_data = databaseValues.getJSONObject(i);

			final String databasePassword = json_data.getString("password");
			
			//if password matches, continue to main activity
			if (password.equals(databasePassword)) {
				Constants.USER_NAME = username;
				Intent myIntent = new Intent(this, MainActivity.class);
				startActivity(myIntent);
			} else {
				Toast.makeText(this, "Password is incorrect.", Toast.LENGTH_LONG).show();
			}
		}
		
		
	}

	private class LoginOperation extends AsyncTask<String, Void, String> {

		JSONArray returnValue;

		@Override
		protected String doInBackground(String... params) {

			String query = null;
			try {
				query = "?username=" + URLEncoder.encode(params[0], "UTF-8")
						+ "&password=" + URLEncoder.encode(params[1], "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			returnValue = DatabaseFunctions
					.getJSONArray(Constants.LOGIN, query);
			return null;

		}

		@Override
		protected void onPostExecute(String result) {

			try {
				checkUserNameAndPassword(returnValue);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
